{% extends 'home.html' %}

{% block content %}
<div class="container-fluid">
    <!-- 查询区域 -->
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">证书下载</h3>
        </div>
        <div class="panel-body">
            <form class="form-inline" method="get" action="{% url 'download' %}">
                <!-- 第一行 -->
                <div class="row" style="margin-bottom: 15px;">
                    <div class="form-group col-md-3">
                        <label for="c_number" style="min-width: 60px;">证书编号</label>
                        <div style="position:relative;">
                            <input type="text" class="form-control clearable-input" id="c_number" name="c_number" 
                                value="{{ search_params.c_number }}" style="width: 250px">
                            <span class="clear-btn" style="display:none;">×</span>
                        </div>
                    </div>
                    <div class="form-group col-md-3">
                        <label for="approve" style="min-width: 60px;">证书状态</label>
                        <div style="position:relative;">
                            <select class="form-control clearable-input" id="approve" name="approve" style="width: 250px; padding-right: 25px;">
                                <option value="">全部</option>
                                <option value="1" {% if search_params.approve == '1' %}selected{% endif %}>未审批</option>
                                <option value="2" {% if search_params.approve == '2' %}selected{% endif %}>已审批</option>
                                <option value="3" {% if search_params.approve == '3' %}selected{% endif %}>撤回</option>
                                <option value="4" {% if search_params.approve == '4' %}selected{% endif %}>校准废弃</option>
                            </select>
                            <span class="clear-btn {% if not search_params.approve %}d-none{% endif %}">×</span>
                        </div>
                    </div>

                    <div class="form-group col-md-3">
                        <label for="type" style="min-width: 60px;">校准类型</label>
                        <div style="position:relative;">
                            <select class="form-control clearable-input" id="type" name="type" style="width: 250px; padding-right: 25px;">
                                <option value="">全部</option>
                                <option value="KFC" {% if search_params.type == 'KFC' %}selected{% endif %}>KFC</option>
                                <option value="KFV" {% if search_params.type == 'KFV' %}selected{% endif %}>KFV</option>
                                <option value="DWY" {% if search_params.type == 'DWY' %}selected{% endif %}>DWY</option>
                                <option value="PH" {% if search_params.type == 'PH' %}selected{% endif %}>PH</option>
                                <option value="HMA" {% if search_params.type == 'HMA' %}selected{% endif %}>HMA</option>
                                <option value="LZ" {% if search_params.type == 'LZ' %}selected{% endif %}>LZ</option>
                                <option value="DDL" {% if search_params.type == 'DDL' %}selected{% endif %}>DDL</option>
                            </select>
                            <span class="clear-btn {% if not search_params.type %}d-none{% endif %}">×</span>
                        </div>
                    </div>
                    <div class="form-group col-md-3">
                        <label for="customer" style="min-width: 60px;">客户</label>
                        <div style="position:relative;">
                            <input type="text" class="form-control clearable-input" id="customer" name="customer" 
                                value="{{ search_params.customer }}" style="width: 250px;">
                            <span class="clear-btn" style="display:none;">×</span>
                        </div>
                    </div>
                </div>

                <!-- 第二行 -->
                <div class="row">
                    <div class="form-group col-md-3">
                        <label for="calibrator" style="min-width: 60px;">校准人</label>
                        <div style="position:relative;">
                            <input type="text" class="form-control clearable-input" id="calibrator" name="calibrator" 
                                value="{{ search_params.calibrator }}" style="width: 250px;">
                            <span class="clear-btn" style="display:none;">×</span>
                        </div>
                    </div>
                    <div class="form-group col-md-3">
                        <label for="start_date" style="min-width: 60px;">起始日期</label>
                        <input type="date" class="form-control" id="start_date" name="start_date" 
                            value="{% firstof search_params.start_date three_months_ago|date:'Y-m-d' %}" 
                            style="width: 250px;">
                    </div>
                    <div class="form-group col-md-3">
                        <label for="end_date" style="min-width: 60px;">结束日期</label>
                        <input type="date" class="form-control" id="end_date" name="end_date" 
                            value="{% firstof search_params.end_date today|date:'Y-m-d' %}" 
                            style="width: 250px;">
                    </div>
                    <div class="form-group col-md-3 text-center">
                        <button type="submit" class="btn btn-primary pull-right">查询</button>
                    </div>
                </div>
            </form>
        </div>
        <div class="panel-body">
            <table class="table table-condensed"
                    id="table"
                    data-minimum-count-columns="2">
                <thead>
                    <tr>
                        <th width="5%">
                            <input type="checkbox" id="selectAll">
                        </th>
                        <th>校准类型</th>
                        <th>序列号</th>
                        <th>仪器型号</th>
                        <th>证书编号</th>
                        <th>客户</th>
                        <th>校准日期</th>
                        <th>校准状态</th>
                        <th>校准人</th>
                    </tr>
                </thead>
                <tbody>
                    {% for item in queryset %}
                    <tr>
                        <td>
                            <input type="checkbox" name="cert_ids" value="{{ item.type }}:{{ item.id }}" 
                                   class="cert-checkbox" {% if item.selected %}checked{% endif %}>
                        </td>
                        <td>{{ item.type }}</td>
                        <td>{{ item.all_data.A1PH_SN04|default:"" }}</td>
                        <td>{{ item.all_data.A1PH_ProdModel03|default:"" }}</td>
                        <td>{{ item.c_number }}</td>
                        <td>{{ item.customer }}</td>
                        <td>{{ item.date }}</td>
                        <td>
                            {% if item.approve == 1 %}
                            <span>未审批</span>
                            {% elif item.approve == 2 %}
                            <span>已审批</span>
                            {% elif item.approve == 3 %}
                            <span>撤回</span>
                            {% elif item.approve == 4 %}
                            <span>校准废弃</span>
                            {% endif %}
                        </td>
                        <td>{{ item.all_data.calibrator}}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
            <!-- 分页 -->
            <ul class="pagination pagination-sm">
                {{ page_string|safe }}
            </ul>
        </div>
        <div class="panel-body">
            <form class="form-inline" method="post" id="batchExportForm">
                {% csrf_token %}
                <div class="form-group" style="display: flex; align-items: center;">
                    <div style="flex: 1; display: flex; align-items: center; margin-right: 15px;">
                        <label for="publish_date" style="margin-right: 10px; min-width: 80px;">发布日期</label>
                        <input type="date" class="form-control" id="publish_date" name="publish_date"
                            value="{{ today|date:'Y-m-d' }}" required style="flex: 1;">
                    </div>
                    <div style="flex: 1; display: flex; justify-content: center; margin-right: 15px;">
                        <button type="button" class="btn btn-success" id="batchExportBtn" style="width: 70%;">
                            <i class="glyphicon glyphicon-download-alt"></i> 导出选中证书
                        </button>
                    </div>
                    <div style="flex: 1; display: flex; justify-content: center;">
                        <button type="button" class="btn btn-success" id="batchExportBtnIcon" style="width: 70%;">
                            <i class="glyphicon glyphicon-download-alt"></i> 导出选中证书【图标版本】
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
$(document).ready(function() {
    // 全选/全不选功能
    $('#selectAll').change(function() {
        const isChecked = $(this).prop('checked');
        $('.cert-checkbox').prop('checked', isChecked);
    });

    // 单个复选框改变时检查全选状态
    $('#table').on('change', '.cert-checkbox', function() {
        const totalCheckboxes = $('.cert-checkbox').length;
        const checkedCount = $('.cert-checkbox:checked').length;
        $('#selectAll').prop('checked', totalCheckboxes === checkedCount && totalCheckboxes > 0);
    });

    // 显示/隐藏清除按钮并处理点击事件
    $('.clearable-input').each(function() {
        const $input = $(this);
        const $clearBtn = $input.next('.clear-btn');
        
        // 根据输入值显示/隐藏清除按钮
        function toggleClearBtn() {
            $clearBtn.toggle($input.val().length > 0);
        }
        
        // 初始化状态
        toggleClearBtn();
        
        // 输入变化时更新
        $input.on('input propertychange', toggleClearBtn);
        
        // 点击清除按钮
        $clearBtn.click(function() {
            $input.val('');
            toggleClearBtn();
            $input.closest('form').submit();
        });
    });

     // 修改后的日期设置函数
    const setDefaultDates = () => {
        const today = new Date();
        const threeMonthsAgo = new Date();
        threeMonthsAgo.setDate(today.getDate() - 90);
        
        const formatDate = (date) => {
            return date.toISOString().split('T')[0];
        };
        
        // 获取当前URL参数
        const urlParams = new URLSearchParams(window.location.search);
        
        // 只有当URL中完全没有日期参数时才设置默认值
        if (!urlParams.has('start_date') && !urlParams.has('end_date')) {
            document.getElementById('start_date').value = formatDate(threeMonthsAgo);
            document.getElementById('end_date').value = formatDate(today);
        }
    };

    // 调用修改后的函数
    setDefaultDates();

    // 普通版本导出按钮点击事件
    $('#batchExportBtn').click(function() {
        const publishDate = $('#publish_date').val();
        if (!publishDate) {
            alert('请填写发布日期');
            return;
        }

        // 格式化日期为YYYYMMDD
        const formattedDate = publishDate.replace(/-/g, '');

        const selectedItems = $('.cert-checkbox:checked').map(function() {
            return $(this).val(); // 直接返回值而不是对象
        }).get();
        
        if(selectedItems.length === 0) {
            alert('请至少选择一条记录');
            return;
        }

        if(selectedItems.length === 1) {
            // 单个文件下载，使用原来的URL
            const [type, pk] = selectedItems[0].split(':');
            const downloadUrl = `/approve/${type}/${pk}/report/?publish_date=${encodeURIComponent(formattedDate)}`;
            window.location.href = downloadUrl;
        } else {
            // 多个文件下载，使用批量下载URL
            if(!confirm(`确定要下载${selectedItems.length}个证书吗？`)) {
                return;
            }
            
            // 构造包含所有证书信息的参数
            const certsParam = selectedItems.join(',');
            const downloadUrl = `/approve/reportbatch/?certs=${encodeURIComponent(certsParam)}&publish_date=${encodeURIComponent(formattedDate)}`;
            window.location.href = downloadUrl;
        }
    });

    // 图标版本导出按钮点击事件
    $('#batchExportBtnIcon').click(function() {
        const publishDate = $('#publish_date').val();
        if (!publishDate) {
            alert('请填写发布日期');
            return;
        }

        // 格式化日期为YYYYMMDD
        const formattedDate = publishDate.replace(/-/g, '');

        const selectedItems = $('.cert-checkbox:checked').map(function() {
            return $(this).val(); // 直接返回值而不是对象
        }).get();
        
        if(selectedItems.length === 0) {
            alert('请至少选择一条记录');
            return;
        }

        if(selectedItems.length === 1) {
            // 单个文件下载，使用原来的URL
            const [type, pk] = selectedItems[0].split(':');
            const downloadUrl = `/approve/${type}/${pk}/report/?publish_date=${encodeURIComponent(formattedDate)}&icon_version=true`;
            window.location.href = downloadUrl;
        } else {
            // 多个文件下载，使用批量下载URL
            if(!confirm(`确定要下载${selectedItems.length}个证书吗？（图标版本）`)) {
                return;
            }
            
            // 构造包含所有证书信息的参数
            const certsParam = selectedItems.join(',');
            const downloadUrl = `/approve/reportbatch/?certs=${encodeURIComponent(certsParam)}&publish_date=${encodeURIComponent(formattedDate)}&icon_version=true`;
            window.location.href = downloadUrl;
        }
    });

});
</script>
{% endblock %}

{% block css %}
<style>
    /* 标签样式 */
    label {
        display: inline-block;
        margin-right: 10px;
        margin-bottom: 0;
        min-width: 80px; /* 统一标签宽度 */
        text-align: right;
    }

    /* 调整表单组布局 */
    .form-group {
        display: flex;
        align-items: center;
        margin-bottom: 15px; /* 调整行间距 */
    }

    /* 输入控件样式 */
    .form-control {
        flex: 1;
        min-width: 0; /* 防止内容溢出 */
    }
    
    /* 可清除输入框样式 */
    .clear-btn {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
        color: #aaa;
        z-index: 10;
    }

    .clear-btn:hover {
        color: #333;
    }

    /* 调整列宽 */
    .form-group.col-md-3 {
        width: 25%;
        padding-left: 10px;
        padding-right: 13px;
    }
    
    /* 按钮位置调整 */
    .btn-primary {
        padding: 6px 20px;
    }

    /* 分页组件间距归零 */
    .pagination {
        margin-top: 0;
        margin-bottom: 0;
    }
</style>
{% endblock %}